/**
 * @description: 全员营销活动|添加或修改
 *
 * @author Yangcl
 * @date 2018年6月27日 下午17:04:28
 * @version 1.0.0.1
 */
var aemInfoOperate = {
		
		path : null,
		aemDiv : null,
		participationDiv : null,
		rewardDiv : null,
		org : null,  
		status : null,
		orgIdList : null,     // 编辑时保存部门id列表
		
		init : function(status_){
			aemInfoOperate.aemTypeSelect();
			aemInfoOperate.status = status_;
			return aemInfoOperate;
		},
		
		// 初始化下拉框
		aemTypeSelect : function(){
			var data = null;
			var url = aemInfoOperate.getPath() +"/aemInfo/ajaxAemTypeList"; 
			var e = JSON.parse(aemInfoOperate.syncAjax("post", url , data , false)); 
			if(e.status == "200"){
				var arr = e.list;
				var html_ = '<option value="0">请选择活动类型</option>';  
				for(var i = 0 ; i < arr.length ; i ++){
					html_ += '<option value="' + arr[i].id + '">' + arr[i].name + '</option>'; 
				}
				$("#aem-type-id").append(html_); 
			}else{
				var html_ = '<option value="0">请选择活动类型</option>';  
				$("#aem-type-id").append(html_); 
			}
		},
		
		// 创建营销活动 下一步按钮
		aemDivNext : function(){
			if(aemInfoOperate.aemDivValidate()){
				$(".row-div-block").hide();
				$("#participation-div").show();  
				$("#row-div-tip")[0].innerHTML = "设置参与人群";  
				$("#stype-2").addClass("s_current");  
				aemInfoOperate.aemDiv = $("#aem").serializeArray();
				// 如果是编辑行为则 ztree反选 
				if(aemInfoOperate.orgIdList != null && aemInfoOperate.orgIdList.length != 0){
					var tree = $.fn.zTree.getZTreeObj("tree");
					var nodes = tree.transformToArray(tree.getNodes()); 
		        	if(nodes.length == 0){
		        		return;
		        	}
		        	for(var n = 0 ; n < nodes.length ; n ++){
		        		tree.checkNode(nodes[n], false, false); 
		        	}
		        	var arr = aemInfoOperate.orgIdList
		        	for(var n = 0 ; n < nodes.length ; n ++){
		        		for(var i = 0 ; i < arr.length ; i ++){
		            		if(nodes[n].id == arr[i]){
		            			tree.checkNode(nodes[n], true, false); 
		            		}
		            	} 
		        	} 
				}
			}
		},
		
		aemDivValidate : function(){
			if(aemInfoOperate.trim($("#aem-name").val()).length == 0 ){
				aemInfoOperate.pageMessage("验证" , "请输入活动名称");
				return false;
			}
			/*if($("#aem-type-id").val() == "" ){             Fuck pm's idea          s of bitch                                                 
				aemInfoOperate.pageMessage("验证" , "请选择活动类型");
				return false;
			}*/
			if(aemInfoOperate.trim($("#start-time").val()).length == 0 ){
				aemInfoOperate.pageMessage("验证" , "请选择活动时间");  // 活动开始时间不可为空
				return false;
			}
			if(aemInfoOperate.trim($("#end-time").val()).length == 0 ){
				aemInfoOperate.pageMessage("验证" , "请选择活动时间");   // 活动结束时间不可为空
				return false;
			}
			if($("#h5-aem-info").children().length == 0){
				aemInfoOperate.pageMessage("验证" , "H5素材不可为空");
				return false;
			}
			if(aemInfoOperate.trim($("#pic").val()).length == 0 ){
				aemInfoOperate.pageMessage("验证" , "请上传活动图片");
				return false;
			}
			
			return true;
		},

		// 设置参与人群 上一步按钮
		participationDivBack : function(){
			$(".row-div-block").hide();
			$("#aem-div").show();  
			$("#row-div-tip")[0].innerHTML = "创建营销活动";  
			$("#stype-2").removeClass("s_current");  
			aemInfoOperate.participationDiv = null;
			aemInfoOperate.org = null;
		},
		
		
		// 设置参与人群 下一步按钮
		participationDivNext : function(){
			if(aemInfoOperate.participationDivValidate()){
				$(".row-div-block").hide();
				$("#reward-div").show();  
				$("#row-div-tip")[0].innerHTML = "设置奖励规则";  
				$("#stype-3").addClass("s_current");  
				
				aemInfoOperate.participationDiv = $("#participation").serializeArray();
				aemInfoOperate.participationDiv.push(aemInfoOperate.org); 
			}
		},
		
		participationDivValidate : function(){
			var tree = $.fn.zTree.getZTreeObj("tree");
	    	var checkArray = tree.getChangeCheckedNodes(); // 获取所有被选节点 
	    	var ids = ''; 
	    	for(var i = 0 ; i < checkArray.length ; i ++){
	    		var t = checkArray[i];
	    		if(t.navType != -1){
	    			ids += t.id + ",";
	    		}
	    	}
	    	ids = ids.substring(0 , ids.length -1); 
	    	if(aemInfoOperate.trim(ids).length == 0){
	    		aemInfoOperate.pageMessage("验证" , "请选择发布部门");
				return false;
	    	}
	    	
	    	aemInfoOperate.org = new Object();
	    	aemInfoOperate.org.name = "orgIds";
	    	aemInfoOperate.org.value = ids;
	    	return true;
		},
		
		
		// 设置奖励规则 上一步按钮
		rewardDivBack : function(){
			$(".row-div-block").hide();
			$("#participation-div").show();  
			$("#row-div-tip")[0].innerHTML = "设置参与人群";  
			$("#stype-3").removeClass("s_current");  
			
			aemInfoOperate.rewardDiv = null;
		},
		
		// 添加状态的提交操作
		rewardDivSubmit : function(o){
			if(aemInfoOperate.rewardDivValidate()){
				if(aemInfoOperate.aemDiv.length == 6 || aemInfoOperate.aemDiv.length == 7){
//					aemInfoOperate.aemDiv;
//					aemInfoOperate.participationDiv;
					for(var i = 0 ; i < aemInfoOperate.participationDiv.length ; i ++){
						aemInfoOperate.aemDiv.push(aemInfoOperate.participationDiv[i]);
					}
					aemInfoOperate.rewardDiv = $("#reward").serializeArray();
					for(var k = 0 ; k < aemInfoOperate.rewardDiv.length ; k ++){
						aemInfoOperate.aemDiv.push(aemInfoOperate.rewardDiv[k]);
					}
				}
				
				var data = aemInfoOperate.aemDiv;
				for(var i in data){
					if(data[i].name == "startTime"){
						data[i].value=data[i].value+" 00:00:00";
					}
					
					if(data[i].name == "endTime"){
						data[i].value=data[i].value+" 23:59:59";
					}
				}
				var url = aemInfoOperate.getPath();
				var type = $(o).attr("atype");
				if(type == "add"){
					url += "/aemInfo/ajaxAddAemInfo"; 
				}else{
					url += "/aemInfo/ajaxEditAemInfo"; 
				}
				var e = JSON.parse(aemInfoOperate.syncAjax("post", url , data , false)); 
				if(e.status == "200"){
//					aemInfoOperate.pageMessageBack("操作提示" , "操作成功!");
					window.location.href = aemInfoOperate.getPath() + "/view/ui/aemInfoPage";
				}else{
					aemInfoOperate.pageMessage("操作提示" , e.message);
				}
			}
		},
		
		rewardDivValidate : function(){
			if( !aemInfoOperate.validateNum($("#share-score").val() )){
				aemInfoOperate.pageMessage("验证" , "分享积分不可为空, 且为正整数"); 
				return false;
			}
			if( !aemInfoOperate.validateNum($("#click-sore").val() )){
				aemInfoOperate.pageMessage("验证" , "点击积分不可为空, 且为正整数"); 
				return false;
			}	
			if(aemInfoOperate.trim($("#share-note").val()).length == 0 ){
				aemInfoOperate.pageMessage("验证" , "奖励说明不能为空"); 
				return false;
			}
			return true;
		},
		
		// 编辑页信息回显
		drawEditPage : function(id_){
			var data = {
				id : id_	
			};
			var url = aemInfoOperate.getPath() + "/aemInfo/ajaxFindAemInfo"; 
			var e = JSON.parse(aemInfoOperate.syncAjax("post", url , data , false)); 
			if(e.status == "200"){  // draw edit page beginning
				$("#aem-id").val(e.info.id);  
				$("#aem-name").val(e.info.name);
				$("#aem-name-old").val(e.info.name);
				$("#aem-type-id").find("option[value='" + e.info.aemTypeId + "']").prop("selected",true);
				$("#start-time").val( e.info.startTime.substring(0 , e.info.startTime.length - 11) );
				$("#end-time").val( e.info.endTime.substring(0 , e.info.endTime.length - 11) );
				$("#mgi-name").text(e.mgi);
				$("#card_image").attr("src" , e.info.pic);
				$("#pic").val(e.info.pic);
				$("#share-note").val(e.info.bonusNote);
				$("input[name='isStaffFirst'][value='" + e.info.isStaffFirst + "']").prop("checked","checked");
				
				var arr = e.aidList;
				if(arr != null){
					aemInfoOperate.orgIdList = new Array();
					for(var i = 0 ; i < arr.length ; i++){
						aemInfoOperate.orgIdList.push(arr[i].companyDepartmentId);  // 准备下一步时回显ztree数据
					}
				}
				
				$("#aem-level").find("option[value='" + e.info.countShareLevel + "']").prop("selected",true);
				$("#share-score").val(e.info.shareScore);
				$("#click-sore").val(e.info.clickSore);  
				
				aemInfoOperate.initPageStatus();
			}else{
				aemInfoOperate.pageMessage("操作提示" , e.message);
			}
		},
		
		// 初始化编辑页面状态
		initPageStatus : function(){
			var s = aemInfoOperate.status; 
			if(s == "2" || s == "3"){
				var op = $("#aem-level").find("option:checked");
				$("#aem-level").children().remove();
				$("#aem-level").append(op);
				$("#share-score").attr("readonly" , true);
				$("#click-sore").attr("readonly" , true);
			}
			if(s == "3"){
				$("#aem-name").attr("readonly" , true); 
				var op = $("#aem-type-id").find("option:checked");
				$("#aem-type-id").children().remove();
				$("#aem-type-id").append(op);
				
				$("#start-time").attr("readonly" , true);
				$("#end-time").attr("readonly" , true);
				$("#x_inputfile").remove();
				$("#edit-btn").remove();
			}
		},
		
		// 创建新的H5素材
		showH5Page : function(){
			window.location.href = aemInfoOperate.getPath() + "/material/teletextMaterialCreate?handleType=create";
		},
		
		// 展示H5素材列表
		showH5Dialog : function(){
			if(aemInfoOperate.trim($("#start-time").val()) == "" || aemInfoOperate.trim($("#end-time").val()) == ""){
				aemInfoOperate.pageMessage("验证" , "请选择活动时间");
				return ;
			}
			var data = {
					stime : $("#start-time").val()+ " 00:00:00",
					etime : $("#end-time").val()+ " 23:59:59"
			}
			dialogPage.init("h5-dialog-list" , "page-list" , "/aemInfo/ajaxMaterialGraphicInfoPageList" , data , 6 ).loadDialogPage();
		},
		
		// 选定H5素材，目前需求仅添加可用
		selectMgi : function(){
			if($("input[name='mgi']:checked").length != 0){
				$("#h5-aem-info").children().remove();  
				var zid = $("input[name='mgi']:checked").val();
				var name = $("input[name='mgi']:checked").parent().parent().children()[1].innerHTML;
				
				var html = '<input type="hidden" name="mgiId" value="' + zid + '">'
						+ '<span style="border:1px #F19736 solid;padding:2px;border-radius: 3px;">' + name +'</span> '
						+ '<img class="x_lista" src="../../images/marketing/close.png" onclick="aemInfoOperate.deleteH5(this)">';
				$("#h5-aem-info").append(html);
			}
			dialogPage.closeDialog();
		},
		
		// h5弹窗的搜索按钮
		h5DialogSearch : function(){
			var arr = new Array();
			var o = Object();
			o.name = "name";
			o.value = $("#dialog-name").val();  
			arr.push(o);
			dialogPage.search(arr);
		},
		
		// 删除活动内容下的H5素材
		deleteH5 : function(e){
			$(e).parent().children().remove();
		},
		
		// 消息提示对话框
		pageMessage : function(title_ , msg_){
			swal({
				  title: title_,
				  text: msg_,
				  type: 'warning',
				  showCancelButton: false,
				  confirmButtonColor: '#d33',
				  confirmButtonText: '确定' 
				})
		},
		
		pageMessageBack : function(title_ , msg_){
			swal({
				  title: title_,
				  text: msg_,
				  type: 'warning',
				  showCancelButton: false,
				  confirmButtonColor: '#d33',
				  confirmButtonText: '确定' 
				}).then(function () {
					window.location.href = aemInfoOperate.getPath() + "/view/ui/aemInfoPage";
				})
		},
		
		
		//验证正整数
		 validateNum:function(value_){
		    var value = aemInfoOperate.trim(value_); 
		    if(value == ""){
		    	return false;
		    }
		    var reg =  /^[1-9]\d*$/;    
		    return reg.test(value);
		},
		
		// aemInfoOperate.getPath()
		getPath : function(){ 
			/*var parse = aemInfoOperate.parseUrl(window.location.href);  
			var path = parse.protocol + '://' + parse.host + ':' + parse.port;
			if("scrm_sps" == parse.segments[0]){
				path +=  '/' + parse.segments[0];
			}*/
			return window.parent.servicePath;
		},
		
		trim : function(str) {
		    return str.replace(/(^\s+$)/g, "");
		},
		
		/**
		 * 发送ajax请求
		 * 
		 * type_ : post or get
		 * url_ : url 
		 * data_ : data_
		 * async_ : sync type ,true or false
		 */
		syncAjax : function(type_, url_, data_  , async_) {
			var msg_ = null;
			$.ajax({
					dataType : "text",
					type : type_,
					url : url_,
					data : data_,
					async : async_, 
					success : function(msg) {
							msg_ = msg;
					},
					error : function(msg) {
							msg_ = msg;
					}
			});
			return msg_;
		},
		
		parseUrl : function(url) {
	        var a =  document.createElement('a');
	        a.href = url;
	        return {
	            source: url,
	            protocol: a.protocol.replace(':',''),
	            host: a.hostname,
	            port: a.port,
	            query: a.search,
	            params: (function(){
	                var ret = {},
	                    seg = a.search.replace(/^\?/,'').split('&'),
	                    len = seg.length, i = 0, s;
	                for (;i<len;i++) {
	                    if (!seg[i]) { continue; }
	                    s = seg[i].split('=');
	                    ret[s[0]] = s[1];
	                }
	                return ret;
	            })(),
	            file: (a.pathname.match(/\/([^\/?#]+)$/i) || [,''])[1],
	            hash: a.hash.replace('#',''),
	            path: a.pathname.replace(/^([^\/])/,'/$1'),
	            relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [,''])[1],
	            segments: a.pathname.replace(/^\//,'').split('/')
	        };
	    }
}



















